//
//  PopoverAnimator.swift
//  todaySwift
//
//  Created by ChokWah on 2018/4/7.
//  Copyright © 2018年 ChokWah. All rights reserved.
//

import UIKit
import ReplayKit
class PopoverAnimator: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
    // 需要展现视图的大小
    var presentFrame: CGRect?
    // 记录当前是打开还是关闭
    var isPresent: Bool = false
    
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        let pc = MyPresentationController(presentedViewController: presented, presenting: presenting)
        pc.presentFrame = presentFrame
        return pc
    }
    // 展开关闭
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        if isPresent {
            // 拿到展现的视图
            let toView = transitionContext.view(forKey: .to)
            toView?.transform = CGAffineTransform(scaleX: 0, y: 0)
            transitionContext.containerView.addSubview(toView!)
            // 执行动画
            UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
                toView?.transform = .identity
            }, completion: { (_) in
                transitionContext.completeTransition(true)
            })
        }else { // 关闭
            // 拿到关闭的视图
            let fromView = transitionContext.view(forKey: .from)
            // 执行动画
            UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
                fromView?.transform = CGAffineTransform(scaleX: 0, y: 0)
            }, completion: { (_) in
                transitionContext.completeTransition(true)
            })
        }
    }
    
    // 展开动画效果
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresent = true
        return self
    }
    
    // 消失动画效果
    func animatorController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresent = false
        return self
    }
    
    // 动画时长
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.25
    }
    
}
